

import $ from 'jquery'
export const uuid = ()=> {
  var s = [];
  var hexDigits = "0123456789abcdef";

  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }

  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010

  s[19] = hexDigits.substr(s[19] & 0x3 | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01

  s[8] = s[13] = s[18] = s[23] = "-";
  var uuid = s.join("");
  return uuid;
}
// 判断是否为空
export const isNull = (val) => {
  if (typeof val == 'boolean') {
    return false;
  }
  if (typeof val == 'number') {
    return false;
  }
  if (val instanceof Array) {
    if (val.length == 0) return true;
  } else if (val instanceof Object) {
    if (JSON.stringify(val) === '{}') return true;
  } else {
    if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true;
    return false;
  }
  return false;
}

export const getHtmlPlainText = (html_str) => {
  //提取字符串中的文字
  let text = '';
  if (html_str) {
    let regrule = new RegExp('<[^<>]+>', 'g')
    text = html_str.replace(regrule, '')
    //或
    //var text = html_str.replace(/<[^<>]+>/g, "");
    text = text.replace(/(\n)/g, "");
    text = text.replace(/(\t)/g, "");
    text = text.replace(/(\r)/g, "");
  }

  return text
}


//加载js或css文件
export const loadJsCssFile = (url, type = 'js', dom = "body") => {
  // console.log('load-', url);
  let flag = false;
  return new Promise((resolve) => {
    const head = dom == 'head' ? document.getElementsByTagName('head')[0] : document.body;
    for (let i = 0; i < head.children.length; i++) {
      let ele = head.children[i]
      if ((ele.src || '').indexOf(url) !== -1) {
        flag = true;
        resolve();
      }
    }
    if (flag) return;
    let script;
    if (type === 'js') {
      script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = url;
    } else if (type === 'css') {
      script = document.createElement('link');
      script.rel = 'stylesheet';
      script.type = 'text/css';
      script.href = url;
    }
    head.appendChild(script);
    script.onload = function () {
      resolve();
    };
  });
};




//过滤掉特殊字符
export const filterSpecialChar = (str) => {
  // 使用正则表达式匹配并替换特殊字符
  // \W 匹配任何非单词字符。等价于 '[^a-zA-Z0-9_]'
  // \s 匹配任何空白字符，包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。
  // g 表示全局匹配，即替换所有匹配项，而不只是第一个。
  return str.replace(/[\W\s]|_|-/g, '');
}


//判断数据格式
export const getSomeType = obj => {
  var toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};

//深度复制
export const deepCloneObj = data => {
  var type = getSomeType(data);
  var obj;
  if (type === 'array') obj = [];
  else if (type === 'object') obj = {};
  else return data;
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      data[i] = (() => {
        if (data[i] === 0) {
          return data[i];
        }
        return data[i];
      })();
      if (data[i]) {
        delete data[i].$parent;
      }
      obj.push(deepCloneObj(data[i]));
    }
  } else if (type === 'object') {
    for (var key in data) {
      if (data) {
        delete data.$parent;
      }
      obj[key] = deepCloneObj(data[key]);
    }
  }
  return obj;
};

//数字补零
export const initNum = (num) => {
  return num < 10 ? `0${num}` : num
}

//日期格式化
export const initDate = (oldDate, format = 'yyyy-MM-dd HH:mm:ss') => {
  const date = new Date(oldDate)
  const config = {
    yyyy: date.getFullYear(),
    M: date.getMonth() + 1,
    MM: initNum(date.getMonth() + 1),
    W: date.getDay(),
    WW: initNum(date.getDay()),
    d: date.getDate(),
    dd: initNum(date.getDate()),
    H: date.getHours(),
    HH: initNum(date.getHours()),
    h: date.getHours() > 12 ? (date.getHours() - 12) : date.getHours(),
    hh: initNum(date.getHours()) > 12 ? (initNum(date.getHours()) - 12) : initNum(date.getHours()),
    m: date.getMinutes(),
    mm: initNum(date.getMinutes()),
    s: date.getSeconds(),
    ss: initNum(date.getSeconds()),
    A: date.getHours() < 12 ? 'AM' : 'PM',
    a: date.getHours() < 12 ? 'am' : 'pm'
  }
  const formatConfigs = format.match(/[a-zA-Z]+/g)
  formatConfigs.forEach(item => {
    format = format.replace(item, config[item])
  })
  return format
}

// 获取assets静态资源
export const getAssetsFile = (url) => {
  return new URL(`../assets/images/${url}`, import.meta.url).href;
};

export const getUrlParam = (name)=> {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg);  //匹配目标参数
  if (r != null) return unescape(r[2]); return null; //返回参数值
}

//封装js动态加载css文件
export function addCss(href){
  //判断是否是同文件
  let links = $("link");
  let isHave = false;
  links.each(function (index, element) {
      if($(element).attr('href') === href) {
          isHave = true;
      }
  });
  if (isHave) return;
  let link = document.createElement('link');
  $(link).attr({
      rel:'stylesheet',
      type:'text/css',
      href
  });
  $('head').append(link);
}

/**
 * 动态加载第三方js.css
 * @param {*} src 路径
 * @param {*} isCss 是否为css文件
 */
export function asynLoad(src, isCss = false) {
  return new Promise(res => {
    let el;
    //设置js-map, css-map防止重复追加标签
    let cssMap = new Map();
    let jsMap = new Map();
    if (isCss) {
      let list = document.documentElement.getElementsByTagName('link');
      for (let i = list.length - 1; i >= 0; i--) {
        let item = list[i];
        if (cssMap.get(item.stylesheet) == null) {
          //利用map设置link css
          cssMap.set(item.getAttribute('stylesheet'), i);
        }
      }

      //不存在追加，存在直接返回true
      if (cssMap.get(src) == null) {
        el = document.createElement('link');
        el.rel = 'stylesheet';
        el.href = src;
        appendDiv();
      } else {
        res(true);
      }

    } else {
      let list = document.documentElement.getElementsByTagName('script');
      for (let i = list.length - 1; i >= 0; i--) {
        let item = list[i];
        if (jsMap.get(item.src) == null) {
          //利用map设置src js
          jsMap.set(item.getAttribute('src'), i);
        }
      }
      //不存在追加，存在直接返回true
      if (jsMap.get(src) == null) {
        el = document.createElement('script');
        el.src = src;
        appendDiv();
      } else {
        res(true);
      }
    }

    function appendDiv() {
      document.documentElement.appendChild(el);
      //判断加载状态
      el.onload = el.onreadystatechange = function () {
        if (
          !this.readyState ||
          this.readyState == 'loaded' ||
          this.readyState == 'complete'
        ) {
          res(true);
        }
        this.onload = this.onreadystatechange = null;
      };
    }
  });
}

/**
 * 动态移除第三方js.css
 * @param {*} src 路径
 * @param {*} isCss 是否为css文件
 */
export function asynRemove(src, isCss = false) {
  let el;
  if (isCss) {
    let list = document.documentElement.getElementsByTagName('link');
    for (let i = list.length - 1; i >= 0; i--) {
      let styleValue = list[i].getAttribute('stylesheet');
      if (styleValue && styleValue.indexOf(src) !== -1) {
        el = list[i];
      }
    }
  } else {
    let list = document.documentElement.getElementsByTagName('script');
    for (let i = list.length - 1; i >= 0; i--) {
      let srcValue = list[i].getAttribute('src');
      if (srcValue && srcValue.indexOf(src) !== -1) {
        el = list[i];
      }
    }
  }
  el && document.documentElement.removeChild(el);
}
/**
 * Unicode转字符串
 * @param unicode Unicode字符串，如 "\u003C\u007C\u6253\u65AD\u007C\u003E"
 * @returns 转换后的字符串
 */
export function unicodeToString(unicode) {
  return unicode.replace(/\\u([0-9a-fA-F]{4})/g, (_, hex) => 
    String.fromCodePoint(parseInt(hex, 16))
  );
}